import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_text.dart';
import 'package:get/get.dart';
import 'package:ones/ui.dart';

import '../../resource/language/generated/l10n.dart';
import '../constants/me_assets_constants.dart';
import '../model/follow_model.dart';
import '../user_details_page/user_details_page.dart';
import 'me_followers_controller.dart';

class MeHistoryPage extends StatefulWidget {
  const MeHistoryPage({Key? key}) : super(key: key);

  @override
  _MeHistoryPageState createState() => _MeHistoryPageState();
}

class _MeHistoryPageState extends State<MeHistoryPage> {
  late MeFollowersController _controller;
  late EasyRefreshController _easyRefreshController;

  int pageNum = 1;
  late String _title;

  @override
  void initState() {
    super.initState();
    _controller = Get.put(MeFollowersController());
    _controller.getHistory(pageNum,  true);
    _easyRefreshController = EasyRefreshController();
  }

  @override
  void dispose() {
    _controller.dispose();
    Get.delete<MeFollowersController>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title:  T.current.me_history.text(
            fontSize: 22.sp,
            color: const Color(0xFF1B1B1B),
            weight: TextFontWeight.medium,
          ),
          backgroundColor: const Color(0xFFDCD4FF),
        ),
        body: EasyRefresh(
          controller: _easyRefreshController,
          header: ClassicHeader(
            showText: false,
            position: IndicatorPosition.above,
            iconTheme: IconThemeData(color: const Color(0xFF9299B1), size: 18.w),
          ),
          footer: const ClassicFooter(
            showText: false,
            triggerOffset: 60.0,
          ),
          onRefresh: () async {
            pageNum = 1;
            _controller
                .getHistory(pageNum, false)
                .then(() {
              _easyRefreshController.finishRefresh();
            });
          },
          onLoad: _controller.hasMore.value
              ? () async {
            pageNum++;
            _controller.getHistory( pageNum,
                false);
          }
              : null,
          child: Obx(() {
            var followers = _controller.followers.value;
            var hasMore = _controller.hasMore.value;
            var followersLength = followers.length;
            return followersLength == 0 ? _buildEmpty() :ListView.builder(
              itemCount: followersLength + (hasMore ? 0 : 1),
              itemBuilder: (context, index) {
                if (index < followersLength) {
                  return _historyItem(
                      followers[index], index == followersLength - 1);
                } else {
                  return Padding(
                    padding: EdgeInsets.only(top: 16.h),
                    child: Center(
                        child: T.current.m13_no_more_data.text(
                          fontSize: 12.sp,
                          color: const Color(0xFFA8A8A8),
                          weight: TextFontWeight.regular,
                        )),
                  );
                }
              },
            );
          }),
        ));
  }

  Widget _historyItem(FollowModel follow,bool isLast) {
    return Container(
      padding: EdgeInsets.only(top: 10.h),
      width: MediaQuery.of(context).size.width,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(width: 15.w),
          buildAvatar(follow.toUserHeadUrl, 20.w),
          SizedBox(width: 12.w),
          Expanded(
            flex: 1,
            child: Column(
              children: [
                _buildUserData(follow),
                SizedBox(height: 17.h),
                if (!isLast)
                  Divider(
                    height: 0.5.h,
                    thickness: 0.5.h,
                    color: const Color(0xFFE4E4E4),
                  )
              ],
            ),
          ),
        ],
      ),
    ).onClick(() {
      Get.to(() => UserDetailsPage(userId: (follow.toUserId ?? 0).toString()));
    });
  }

  // 提取头像组件
  Widget buildAvatar(String? url, double radius) {
    return CircleAvatar(
      radius: radius,
      backgroundImage: NetworkImage(url ?? ''),
      child: url == null || url.isEmpty
          ? Image.asset(MeAssetsConstants.iconEmpty, fit: BoxFit.cover)
          : null,
      backgroundColor: Colors.transparent,
    );
  }

  Widget _buildUserData(FollowModel follow) {
    return Row(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildName(follow),
            _buildAbout(follow),
          ],
        ),
        const Spacer(),
        buildTime(follow.visitTime ?? ""),
        SizedBox(width: 25.w),
      ],
    );
  }
  Widget _buildName(FollowModel follow) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(follow.toUserNickname ?? '',
            style: TextStyle(fontSize: 18.sp, color: Colors.black)),
        SizedBox(width: 5.w),
        Image.asset(
            follow.toGender == 0
                ? MeAssetsConstants.iconNv
                : MeAssetsConstants.iconNan,
            width: 16.w,
            height: 16.w)
      ],
    );
  }
  Widget _buildAbout(FollowModel follow) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 2.5.h),
          height: 14.5.h,
          decoration: BoxDecoration(
            color: Color(0xFFFF7575),
            borderRadius: BorderRadius.circular(32.w),
          ),
          child: Text("LV${(follow.memberLevel ?? 0)}",
              style: TextStyle(fontSize: 10.sp, color: Colors.white)),
        ),
        SizedBox(width: 3.w),
        Text(follow.visitDesc ?? T.current.me1_signature,
            style: TextStyle(fontSize: 11.sp, color: Color(0xFFC1C1C1)))
      ],
    );
  }
  Widget buildTime(String time) {
    return Row(
      children: [
        Text(
          time,
          style: TextStyle(fontSize: 12.sp, color: Color(0xFFA8A8A8)),
        ),
      ],
    );
  }
  Widget _buildEmpty() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(
            MeAssetsConstants.iconEmpty,
            fit: BoxFit.contain,
            width: 248.w,
            height: 248.h,
          ),
          Text("",
              style: TextStyle(fontSize: 12.sp, color: Color(0xFFC1C1C1)))
        ],
      ),
    );
  }
}
